/**
 * 
 */
package de.mbenning.fsim.web.controller.vereine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import de.mbenning.fsim.domain.Adresse;
import de.mbenning.fsim.domain.Land;
import de.mbenning.fsim.domain.Verein;
import de.mbenning.fsim.persistence.dao.interfaces.IMainDAO;
import de.mbenning.fsim.persistence.dao.interfaces.IVereinDAO;
import de.mbenning.fsim.web.controller.AbstractFsimBaseController;
import de.mbenning.fsim.web.servlet.ServletRequestHelper;

/**
 * @author Martin.Benning
 *
 */
public class VereinEditFormController extends AbstractFsimBaseController {
	
	private IVereinDAO vereinDAO;
	
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer vereinId = ServletRequestUtils.getIntParameter(request, "vereinId", -1);
		Verein verein = null;
		if(vereinId.intValue() > 0) {
			verein = vereinDAO.getVereinById(vereinId);
		} else {
			verein = new Verein();
			verein.setAdresse(new Adresse());
		}
		
		return verein;
	}
	
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		List<Land> laender = mainDAO.findAllLaender();
		
		model.put("laender", laender);
		
		return model;
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
		super.onBindAndValidate(request, command, errors);
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Verein verein = (Verein) command;
		
		String wappen = ServletRequestHelper.uploadFile(request, "wappenImage");
		if(wappen != null && !wappen.equals("")) {
			verein.setWappen(wappen);
		}
		
		mainDAO.store(verein);
		return new ModelAndView(new RedirectView("vereineList.htm"));
	}
	
	public IMainDAO getMainDAO() {
		return mainDAO;
	}

	public void setMainDAO(IMainDAO mainDAO) {
		this.mainDAO = mainDAO;
	}

	public IVereinDAO getVereinDAO() {
		return vereinDAO;
	}

	public void setVereinDAO(IVereinDAO vereinDAO) {
		this.vereinDAO = vereinDAO;
	}

}
